package com.kakarote.bi.common;

import com.kakarote.core.feign.crm.entity.BiEntityParams;
import com.kakarote.core.redis.Redis;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author hmb
 * crm权限拦截切面
 */
@Aspect
@Component
@Slf4j
public class BiCacheAspect {

    @Autowired
    private Redis redis;

    @Value("${crm.methodCache:false}")
    private Boolean isCache;

    @Around("execution(* com.kakarote.bi.controller..*(..)) && execution(@(org.springframework.web.bind.annotation.*Mapping) * *(..)) && !execution(@(com.kakarote.core.common.ParamAspect) * *(..))")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        BiEntityParams biParams = null;
        for (Object arg : point.getArgs()) {
            if (arg instanceof BiEntityParams) {
                biParams = (BiEntityParams) arg;
                break;
            }
        }
        if (biParams == null) {
            return point.proceed();
        }
        String generateKey = biParams.generateKey() + ":" + point.getSignature().getName();
        if (isCache && redis.exists(generateKey)) {
            log.debug("use cache:{}", generateKey);
            return redis.get(generateKey);
        }
        Object proceed = point.proceed();
        //数据缓存
        redis.setex(generateKey, 300, proceed);
        return proceed;
    }
}
